package com.whfc.iot.dust.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class DustClientHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--register==============");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--unregistered==============");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--inactive==============");
    }

    // 连接成功后，向server发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--active==============");

        for (int cnt = 0; cnt < 10; cnt++) {
            int[] bytes = new int[]{
                    0xfe, 0xdc, 0x01,
                    0x33, 0x72, 0x51, 0x20, 0x88, 0xb3,
                    0x00, 0x00, 0x00, 0x05,
                    0x03,
                    0x00, 0x30,
                    0x00, 0x00, 0x00, 0xff,
                    0x00, 0x00, 0x01, 0x07,
                    0x00, 0x00, 0x03, 0x54,
                    0xff, 0xff, 0xff, 0x9b,
                    0x00, 0x00, 0x02, 0x92,
                    0x00, 0x00, 0x00, 0x01,
                    0x00, 0x00, 0x00, 0x15,
                    0x00, 0x01, 0x8b, 0xcb,
                    0x00, 0x00, 0x01, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00
            };
            ByteBuf buf = Unpooled.buffer(bytes.length);
            for (int b : bytes) {
                buf.writeByte(b);
            }
            System.out.println(ByteBufUtil.prettyHexDump(buf));

            ctx.channel().writeAndFlush(buf);

            TimeUnit.SECONDS.sleep(15);
        }

    }

    // 接收server端的消息，并打印出来
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        logger.info("==============channel--read==============");
        logger.info("the msg type is " + obj.getClass().getName());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
